package gw.com.android.ui.trade.Fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.gwtsz.gts2.hx.R;

import org.json.JSONException;

import butterknife.BindView;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.model.DataManager;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.terminal.GTSDataListener;
import gw.com.android.ui.dialog.PopupConfirmDialog;
import gw.com.android.ui.trade.TradeBusiness;
import gw.com.android.ui.trade.TradeRangeModel;
import gw.com.android.ui.views.NumericEdit;
import gw.com.android.ui.views.OrderBottomView;
import gw.com.android.ui.views.TitleRangeView;
import gw.com.jni.library.terminal.GTSConst;
import www.com.library.app.Logger;
import www.com.library.model.DataItemDetail;
import www.com.library.util.DoubleConverter;
import www.com.library.util.StringFormatter;
import www.com.library.view.NumberInput;

/**
 * 挂单改单界面
 *
 * @author Reeta.zou
 *
 */
public class PendingOrderModifyFragment extends BaseOrderFragment{

	/**产品列表*/
	@BindView(R.id.proNameView)
	TextView mPrdNameView;
	@BindView(R.id.morder_title_price)
	TitleRangeView mPriceTitleView;
	/**下单类型视图*/
	@BindView(R.id.trade_type)
	TextView mTypeView;
	/**手数加减器*/
	@BindView(R.id.morder_input_lot)
	TextView m_lotEditView = null;
	/**价格加减器*/
	@BindView(R.id.morder_input_price)
	NumericEdit m_priceEditView;
	/**期限*/
	@BindView(R.id.day_title)
	TextView m_expireDay;

	/**输入的挂单价*/
	public String mInputPrice = "";
	/**订单id*/
	private int mOrderID = 0;

	/**
	 * 更新通知处理
	 */
	public final Handler HandlerCallback = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case GTSConst.REPLY_SYMBOL_TICK_UPDATE:
				//更新界面价格和范围值
				onConfigDynamicViews();
				updateWithPrice();
				mBottomview.updateProduct(mRangeModel);
				checkError();
				break;
			case AppContances.HANDLER_SCR_UPDATE_INPUTPRICE:
				TradeBusiness.calPendingLossAndWin(mTickModel,mSymbolModel, mRangeModel,mInputPrice, mTradeDir, mPositionModel.getInt(GTSConst.JSON_KEY_ORDERTYPE));
				mBottomview.updateProduct(mRangeModel);
				checkError();
				break;
			}
		}
	};
	
	@Override
	public void setArguments(Bundle args) {
		super.setArguments(args);
		if(args != null){
			mOrderID = args.getInt("id");
			mUiCode = args.getInt("uiCode");
			mPositionModel = DataManager.instance().getOrderModel(mOrderID);
			mTickModel = DataManager.instance().getTickModel(mUiCode);
			updateSymbolModel();
			if(null == mPositionModel || 0 == mUiCode || null == mSymbolModel){
				Logger.e("改单mPositionModel对象为空，出现异常" + mUiCode);
				if (null != getActivity()) {
					getActivity().finish();
				}
				return;
			}
			mSymbol = DataManager.instance().getPrdName(mPositionModel);
			mTradeDir = mPositionModel.getInt(GTSConst.JSON_KEY_DIRECTION);
			mInputPrice = mPositionModel.getString(GTSConst.JSON_KEY_ORDERPRICE);
		}
	}

	@Override
	protected int getLayoutId() {
		return R.layout.fragment_order_modify_apply;
	}

	@Override
	protected void initLayoutView()  {
		super.initLayoutView();
		if(mPositionModel.getInt(GTSConst.JSON_KEY_ORDERTYPE) == AppContances.ORDER_TYPE_APPLY_TYPE){
			mTypeView.setText(AppMain.getAppString(R.string.order_limit_price));
		}else{
			mTypeView.setText(AppMain.getAppString(R.string.order_stop_price));
		}

		if(mTradeDir == AppContances.TRADE_TYPE_BUY){
			m_buyLayout.setSelected(true);
			m_sellLayout.setSelected(false);
		}else{
			m_buyLayout.setSelected(false);
			m_sellLayout.setSelected(true);
		}
		if(mPositionModel.getInt(GTSConst.JSON_KEY_EXPIRETYPE) == AppContances.VALID_TYPE_DAY){
			m_expireDay.setText(AppMain.getAppString(R.string.order_item_trade_expiry_day));
		}else{
			m_expireDay.setText(AppMain.getAppString(R.string.order_item_trade_expiry_week));
		}
		m_priceEditView.setLongClickable(false);
		m_priceEditView.setAfterTextChangedListener(mTextChangedListener);
		m_priceEditView.getNumericInput().setOnFocusChangeListener(this);
		mRootView.findViewById(R.id.morder_container_price);

		m_ConfirmButton.setText("#" + mOrderID + AppMain.getAppString(R.string.order_type_order_modity));

		mBottomview.setPriceType(false);
		mBottomview.setFocusChange(this);
        mBottomview.setErrorCheckLisenter(new OrderBottomView.onErrorCheckLisenter() {
			
			@Override
			public void onErrorCheck() {
				checkError();
			}
		});

		mRangeModel = new TradeRangeModel();
		cmd = AppContances.ORDER_TYPE_APPLY_MODIFY;
	}

	@Override
	protected void initViewData() {
		mPriceTitleView.setTitleView(R.string.order_title_price);
		mPrdNameView.setText(mSymbol);
		m_lotEditView.setText(mPositionModel.getString(GTSConst.JSON_KEY_VOLUME));
		TradeBusiness.calPendingLossAndWin(mTickModel, mSymbolModel,mRangeModel,mInputPrice, mTradeDir, mPositionModel.getInt(GTSConst.JSON_KEY_ORDERTYPE));
		mBottomview.setProductInfo(mRangeModel);
		updateWithPrice();
		onConfigDynamicViews();
		m_priceEditView.setText(mPositionModel.getString(GTSConst.JSON_KEY_ORDERPRICE));
		mDetail.setStringValue("mPrePrice", mPositionModel.getString(GTSConst.JSON_KEY_ORDERPRICE));
		mBottomview.setFoldView(false);
		if (null != mPositionModel.getString(GTSConst.JSON_KEY_STOPLOSS) && !mPositionModel.getString(GTSConst.JSON_KEY_STOPLOSS).isEmpty()
				&& DoubleConverter.toFloatData(mPositionModel.getString(GTSConst.JSON_KEY_STOPLOSS)) > 0) {
			mDetail.setStringValue("mPreLoss",mPositionModel.getString(GTSConst.JSON_KEY_STOPLOSS));
			mBottomview.setLossValue(mPositionModel.getString(GTSConst.JSON_KEY_STOPLOSS));
			mBottomview.setFoldView(true);
		}
		if (null != mPositionModel.getString(GTSConst.JSON_KEY_STOPPROFIT) && !mPositionModel.getString(GTSConst.JSON_KEY_STOPPROFIT).isEmpty()
				&& DoubleConverter.toFloatData(mPositionModel.getString(GTSConst.JSON_KEY_STOPPROFIT)) > 0) {
			mDetail.setStringValue("mPreWin",mPositionModel.getString(GTSConst.JSON_KEY_STOPPROFIT));
			mBottomview.setProfitValue(mPositionModel.getString(GTSConst.JSON_KEY_STOPPROFIT));
			mBottomview.setFoldView(true);
		}
	}

	/**
	 * 设置界面加减器中各属性值
	 */
	public void onConfigDynamicViews() {
		mPriceTitleView.setRangeView(mRangeModel.minRangePrice, mRangeModel.maxRangePrice);
		m_priceEditView.setMinSteps(mRangeModel.pointToPrice);
		m_priceEditView.setMin(Double.MIN_VALUE);
		m_priceEditView.setMax(Double.MAX_VALUE);
		m_priceEditView.setDigits(10, (9-mRangeModel.mDigit), mRangeModel.mDigit);
		m_priceEditView.setDefalutValue(mRangeModel.defalutPrice);
	}

	 /**
     * 输入框文本变化处理
     */
	private final NumberInput.OnTextChangedListener mTextChangedListener = new NumberInput.OnTextChangedListener() {
		@Override
		public void onTextChanged(EditText edit, Editable s) {
			if (TextUtils.isEmpty(edit.getText()) && null != mBottomview) {
//				mBottomview.morder_loss_range.setText("[0-0]");
//				mBottomview.morder_win_range.setText("[0-0]");
			}
			if (edit == m_priceEditView.getNumericInput()) {
				mInputPrice = m_priceEditView.getValueString();
				if (HandlerCallback != null) {
					HandlerCallback.sendEmptyMessage(AppContances.HANDLER_SCR_UPDATE_INPUTPRICE);
			    }
			}
			checkError();
		}
	};
	
	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		mBottomview.onFocusChanged(v, hasFocus);
	
		checkError();
	}
	
	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		if(!hidden){
			checkError();
		}
	}
	
	/**
	 * 检查界面错误
	 * @return
	 */
	private boolean checkError(){
		String errorMessage = "";

		//挂单价格
		String rangePrice = m_priceEditView.getText();
		String errorMessage1 = TradeBusiness.getApplyPriceErrorMsg(mRangeModel.minRangePrice, mRangeModel.maxRangePrice, rangePrice);
		if (!"".equals(errorMessage1)) {
			mPriceTitleView.setErrorColor();
			errorMessage = errorMessage1;
		}else{
			mPriceTitleView.setDefalutColor();
		}

		//检查止损止盈
		String errorMessage2 = mBottomview.checkError();
		if (!"".equals(errorMessage2) && "".equals(errorMessage)) {
			errorMessage = errorMessage2;
		}

		if (isVisible() && null != mStatusListener) {
			mStatusListener.onError(errorMessage);
		}

        if(!"".equals(errorMessage)) {
            return true;
        }else {
            return false;
        }
	}
	
	@Override
	public boolean hasPostData() {
		m_priceEditView.getNumericInput().clearFocus();
		mBottomview.clearAllFocus();
		
		if (checkError()) {
			return false;
		}

		if (!TradeBusiness.PreOrderCheck(getActivity(), mPositionModel.getInt(GTSConst.JSON_KEY_ZONE), mPositionModel.getInt(GTSConst.JSON_KEY_TRADESTATE), true)) {
			return false;
		}

		try {
			mSeq = GTSDataListener.curSeq++;
			GTSDataListener.instance().addSeqList(mSeq+"", cmd+"");
			Logger.e("改单下单的seq == " + mSeq);
			jsonData.put(GTSConst.JSON_KEY_ID, mPositionModel.getInt(GTSConst.JSON_KEY_ID));
			jsonData.put(GTSConst.JSON_KEY_CODEID,mPositionModel.getInt(GTSConst.JSON_KEY_CODEID));
			jsonData.put(GTSConst.JSON_KEY_DIRECTION, mPositionModel.getInt(GTSConst.JSON_KEY_DIRECTION));
			jsonData.put(GTSConst.JSON_KEY_VOLUME,mPositionModel.getString(GTSConst.JSON_KEY_VOLUME));
			jsonData.put(GTSConst.JSON_KEY_ORDERPRICE, m_priceEditView.getText());
			jsonData.put(GTSConst.JSON_KEY_ORDERTYPE, mPositionModel.getInt(GTSConst.JSON_KEY_ORDERTYPE));
			jsonData.put(GTSConst.JSON_KEY_STOPLOSS, mBottomview.getLossPrice());
			jsonData.put(GTSConst.JSON_KEY_STOPPROFIT, mBottomview.getWinPrice());
			jsonData.put(GTSConst.JSON_KEY_EXPIRETYPE, mPositionModel.getInt(GTSConst.JSON_KEY_EXPIRETYPE));
			jsonData.put(GTSConst.JSON_KEY_RANGE, mSymbolModel.getString(GTSConst.JSON_KEY_RANGE));
			jsonData.put(GTSConst.JSON_KEY_USEDIP,0);
			jsonData.put(GTSConst.JSON_KEY_TRADE_SEQ, mSeq);
		} catch (JSONException e){
			e.printStackTrace();
		}

		if (!DoubleConverter.isZero(DoubleConverter.toFloatData(jsonData.optString(GTSConst.JSON_KEY_STOPLOSS)))) {
			mDetail.setStringValue("mLoss", jsonData.optString(GTSConst.JSON_KEY_STOPLOSS));
		} else {
			mDetail.setStringValue("mLoss", "");
		}
		if (!DoubleConverter.isZero(DoubleConverter.toFloatData(jsonData.optString(GTSConst.JSON_KEY_STOPPROFIT)))) {
			mDetail.setStringValue("mWin",jsonData.optString(GTSConst.JSON_KEY_STOPPROFIT));
		} else {
			mDetail.setStringValue("mWin", "");
		}

		mDetail.setStringValue("mCurrentTag", AppContances.TAB_ID_PENDING_MODIFY_ORDER);
		mDetail.setStringValue("mSymbol", mSymbol);
		mDetail.setIntValue("mPositionID", mOrderID);
		mDetail.setIntValue("mPrdCode", mUiCode);
		mDetail.setIntValue("mTradeDir", mTradeDir);
		mDetail.setIntValue("mType", mPositionModel.getInt(GTSConst.JSON_KEY_ORDERTYPE));
		mDetail.setStringValue("mPrice", jsonData.optString(GTSConst.JSON_KEY_ORDERPRICE));

		//判断订单是否做修改
		if (DoubleConverter.isEqual(DoubleConverter.toFloatData(mDetail.getString("mPrePrice")),DoubleConverter.toFloatData(mDetail.getString("mPrice")), mSymbolModel.getInt(GTSConst.JSON_KEY_DIGITS))
				&& DoubleConverter.isEqual(DoubleConverter.toFloatData(mDetail.getString("mPreLoss")),DoubleConverter.toFloatData(mDetail.getString("mLoss")), mSymbolModel.getInt(GTSConst.JSON_KEY_DIGITS))
				&& DoubleConverter.isEqual(DoubleConverter.toFloatData(mDetail.getString("mPreWin")),DoubleConverter.toFloatData(mDetail.getString("mWin")), mSymbolModel.getInt(GTSConst.JSON_KEY_DIGITS))) {
				String errorMessage = ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1029);
			showToastPopWindow(errorMessage);
			return false;
		}

    	return true;
	}
	
	@Override
	public void requstData() {
		int result = AppTerminal.instance().reqOrder(cmd, jsonData.toString());
		if(result != 0){
			if(null != mStatusListener){
				mStatusListener.onFail();
			}
			if(result == 97){
				PopupConfirmDialog.NotifyPrompt(getActivity(), ConfigUtil.instance().mErrorConfigObject.optString(ConfigType.SERVER_ERROR_1016));
			}else{
				PopupConfirmDialog.NotifyPrompt(getActivity(), ConfigUtil.instance().mErrorConfigObject.optString(ConfigType.SERVER_ERROR_1068));
			}
		}
	}

	@Override
	public void onSymbolNotify(DataItemDetail tickModel) {
		if(null != tickModel && mUiCode == tickModel.getInt(GTSConst.JSON_KEY_CODEID)){
			mTickModel = tickModel;
			if(null != mRangeModel){
				TradeBusiness.calPendingLossAndWin(mTickModel,mSymbolModel, mRangeModel,mInputPrice, mTradeDir, mPositionModel.getInt(GTSConst.JSON_KEY_ORDERTYPE));
				HandlerCallback.sendEmptyMessage(GTSConst.REPLY_SYMBOL_TICK_UPDATE);
			}
		}
	}

	@Override
	public void onSymbolNotify() {
		super.onSymbolNotify();
		updateSymbolModel();
	}

	@Override
	public void onOrderSuccessNotify(int notifyId, int orderId, DataItemDetail model) {
		if(mSeq == notifyId){
			Logger.e("改单  orderId == " + orderId);
			mOrderID = orderId;
			if(null != model){
				mDetail.setStringValue("mTime", StringFormatter.instance().secToDateTime(model.getInt(GTSConst.JSON_KEY_TIME)));
				mDetail.setStringValue("mPrice",model.getString(GTSConst.JSON_KEY_ORDERPRICE));

				if (!DoubleConverter.isZero(DoubleConverter.toFloatData(model.getString(GTSConst.JSON_KEY_STOPLOSS)))) {
					mDetail.setStringValue("mLoss", model.getString(GTSConst.JSON_KEY_STOPLOSS));
				} else {
					mDetail.setStringValue("mLoss", "");
				}
				if (!DoubleConverter.isZero(DoubleConverter.toFloatData(model.getString(GTSConst.JSON_KEY_STOPPROFIT)))) {
					mDetail.setStringValue("mWin",model.getString(GTSConst.JSON_KEY_STOPPROFIT));
				} else {
					mDetail.setStringValue("mWin", "");
				}
			}
			if(null != mStatusListener){
				Logger.e("onFragmentOrderUpdate 改单 mStatusListener ");
				mStatusListener.onSuc(mDetail);
			}
		}
	}
}
